package com.fastfly.service;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fastfly.domain.Customer;
import com.fastfly.domain.SecurityQuestion;

@Service("customerService")
@Repository
public class JpaCustomerService extends JpaBase implements CustomerService {

	
	private static final long serialVersionUID = 1L;
	
	public Customer findByFlyNumber(String number) {
		Query query = em.createQuery("select obj from Customer obj where obj.flyNumber = :number ");
		query.setParameter("number", number);
		Customer ret = (Customer) query.getSingleResult();		
		return ret;		
	}
	
	public Customer findBySecurityQuestion(String answer, String email, long securityQuestionId) { 
		Query query = em.createQuery("select obj from Customer obj where obj.question.id = :securityQuestionId and lower(obj.securityAnswer) = :answer and obj.email = :email");
		query.setParameter("answer", answer.toLowerCase());
		query.setParameter("email", email);
		query.setParameter("securityQuestionId", securityQuestionId);
		Customer ret = (Customer) query.getSingleResult();		
		return ret;		
	}	
	

	@Transactional
	public Customer store(Customer customer) {
		customer.enroll();
		em.persist(customer);
		return customer;
	}	
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<SecurityQuestion> findAllSecurityQuestion() {
		List<SecurityQuestion> list = em.createQuery("select obj from SecurityQuestion obj order by obj.question").getResultList();		
		return list;	
	}
	
	

}